package com.zjmcollege.hotpot.controller;

import com.zjmcollege.hotpot.component.FileHandler;
import com.zjmcollege.hotpot.enums.FileType;
import com.zjmcollege.hotpot.exception.ServerException;
import com.zjmcollege.hotpot.exception.UploadFileIsEmpty;
import com.zjmcollege.hotpot.model.UploadResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-19 13:02
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class MdUploadController {
    @Autowired
    private FileHandler fileHandler;

    @RequestMapping("/editormd/{file}")
    public Map<String, Object> uploadImage(
            @PathVariable("file") String fileType,
            @RequestParam(value = "editormd-image-file", required = false)
                    MultipartFile file) {
        Map<String, Object> result  = new HashMap<>();
        result.put("success", 0);
        result.put("message", "上传失败！");

        // 图片类型的资料上传
        if (FileType.IMAGE.name().equals(fileType.toUpperCase())) {
            try {
                UploadResultModel resultModel = fileHandler.upload(file, FileType.IMAGE);
                result.put("success", 1);
                result.put("message", "上传成功！");
                result.put("url", resultModel.getUrl());
            } catch (UploadFileIsEmpty e) {
                e.printStackTrace();
                log.info(e.getLocalizedMessage());
            } catch (ServerException e) {
                e.printStackTrace();
                log.info(e.getLocalizedMessage());
            } finally {
                return result;
            }
        }
        return result;
    }
}
